package com.wtp.wallpaper.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wtp.wallpaper.annotation.ScheduledAnnotation;
import com.wtp.wallpaper.es.service.PictureDocumentService;
import com.wtp.wallpaper.mapper.PictureMapper;
import com.wtp.wallpaper.pojo.entity.Picture;
import com.wtp.wallpaper.service.PictureService;
import com.wtp.wallpaper.utils.AliOssUtil;
import com.wtp.wallpaper.utils.ai.XFXHUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Slf4j
@Component
@ScheduledAnnotation(value = "图片理解",
        cron = "0 0/5 * * * ?",
        description = "定时向讯飞理解图片，五分钟执行一次")
public class ImageUnderstandTask implements Runnable {
    @Autowired
    private XFXHUtil xfxhUtil;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private PictureDocumentService pictureDocumentService;
    @Autowired
    private PictureService pictureService;

    @SneakyThrows
    @Override
    @Transactional
    public void run() {
        log.info("开始处理图片理解,形成描述");
        List<Picture> list = pictureService.lambdaQuery()
                .isNull(Picture::getDescription)
                .or()
                .eq(Picture::getDescription, "")
                .or()
                .eq(Picture::getDescription, "暂无")
                .list();
        list = random(list);
        for (Picture picture : list) {
            String smallpicurl = picture.getSmallpicurl();
            aliOssUtil.getByteFromOSS(smallpicurl);
            String[] strings = xfxhUtil.understandImage(Collections.singletonList(aliOssUtil.getByteFromOSS(smallpicurl)));
            picture.setDescription(strings[0]);
            System.out.println(strings[0]);
            pictureService.updateById(picture);
            pictureDocumentService.update(picture);
        }
    }

    //随机取少量图片来处理一次定时任务处理少量图片方便提交
    private List<Picture> random(List<Picture> list) {
        int length = 20;
        if (list.size() < length) return list;
        int index = (int) (Math.random() * length);
        return list.subList(0, index);
    }
}
